package com.qpx.eurekajpa.aop;


import com.qpx.dto.LogDto;
import com.qpx.eurekajpa.config.Log;
import com.qpx.eurekajpa.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class AopLog {


    @Autowired
    LogService logService;

    //切点
    @Pointcut(" execution(* com.qpx.eurekajpa.controller.*.*(..))")
    public void pointcut(){}

    @AfterReturning(pointcut = "pointcut()")
    public void after(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        LogDto logDto = new LogDto();
        logDto.setRequestType(request.getMethod());
        logDto.setRemoteAddr(request.getRemoteAddr());
        logDto.setServerPort(request.getServerPort()+"");
        logDto.setRequestURI(request.getRequestURI());
        logDto.setArgs(joinPoint.getArgs());
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        logDto.setMethodName(methodName);
        if (method.getAnnotation(Log.class)==null){
            return;
        }
        //组装实体 调用feign 去保存
        logService.save(logDto);
    }

}
